import store from "@/store";
import { authLogin } from "@/api/user";
import { LOCAL_URL, H5_APP_ID, H5_BASE_URL } from "@/config/app";
import { getUserPhoneNumber } from "@/api/public";
import util from "@/utils/util";
import  umaTrack from "@/utils/umaTrack.js";
import { saveLoginEndTime } from "./auth.js";
import cache from "@/utils/cache";
// 微信公众号授权
export async function wxAuthorize(num) {
  // 非静默授权，第一次有弹框
  let local = LOCAL_URL; // 获取页面url
  let appid = H5_APP_ID; // 公众号appid
  let code = await getUrlCode().code; // 截取code
  let spid = (await getUrlCode().state) || 0;
  cache.set("spreadUid", spid);
  const strMap = {
    "H5-dev": "https://dev-manage.julimeng.com/2h5/",
    "H5-test": "https://test-manage.julimeng.com/2h5/",
    "H5-uat": "https://dev-manage.julimeng.com/2h5/",
    "H5-prod": "https://manage.shengdaiqifu.com/2h5/",
  };
  // 获取之前的code
  let oldCode = uni.getStorageSync("wechatCode");
  if (location.href.includes("code") && oldCode) {
    let str = location.href.split("?")[1].split("#")[1];
    window.location.href = location.href.split("/?")[0] + "/#" + str;
    // let a = location.href.split('#/')[1]
    // let b = location.href.split('#/')[0].split('?')[0]
    // location.href = a + '#/' + b
  }
  //判断是否存在code,不存在或者过期将重新授权
  if (code == null || code === "" || code == "undefined" || code == oldCode) {
    // 如果没有code，就去请求获取code
    //转码
    // 设置旧的code为0，避免死循环
    uni.setStorageSync("wechatCode", 0);
    location.replace(
      `${H5_BASE_URL}?appid=${H5_APP_ID}&redirect_uri=${encodeURIComponent(
        strMap[process.env.ENV_TYPE]
      )}&response_type=code&scope=snsapi_userinfo&state=${
        global.spid
      }#wechat_redirect`
    );
    // window.location.href = `${H5_BASE_URL}?appid=${H5_APP_ID}&redirect_uri=${LOCAL_URL}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`;
    uni.setStorageSync("redirecturi", window.location.href);
  } else {
    // 保存最新code
    uni.setStorageSync("wechatCode", code);
    if (code) {
      let par = cache.get("params") && JSON.parse(cache.get("params"));
      let params = {
        code: code,
        ...par,
      };
      let res = await authLogin(params);
      if (res.code === 200) {
        if (res.data.type == "login") {
          await saveLoginEndTime(res.data.expiresIn);
          await store.commit("LOGIN", {
            token: res.data.tokenHead + res.data.token,
          });
          await store.commit("SETUID", res.data.memberId);
          await store.dispatch("USERINFO");
          await umaTrack.loginTrack('微信公众号');
          await util.Tips('登录成功');
        }
        if (res.data.type == "register") {
          // 助融报告页面跳转跟 之前的h5页面跳转需要区分开  之前的无感登录取消  替换未手机号绑定登录
          uni.redirectTo({
            url:
              `/pagesWater/users/login?num=${num}&type=bind&flagType=0&key=` +
              res.data.key,
          });
        }
      }
    }
  }
}


function getUrlCode() {
  // 截取url中的code方法
  var url = location.search;
  // this.winUrl = url;
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
  }
  theRequest.state = theRequest.state == "undefined" ? 0 : theRequest.state;
  return theRequest;
}
